package com.bjpowernode.boss.job;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjpowernode.boss.common.cilent.mail.AttachFile;
import com.bjpowernode.boss.common.cilent.mail.MailClient;
import com.bjpowernode.boss.common.cilent.mail.MailProp;
import com.bjpowernode.boss.db.domain.TradeOrder;
import com.bjpowernode.boss.db.domain.UserInfo;
import com.bjpowernode.boss.db.mapper.TradeOrderMapper;
import com.bjpowernode.boss.db.mapper.UserPayInfoMapper;
import com.bjpowernode.boss.job.header.EachDayBillHeader;
import com.bjpowernode.boss.web.models.result.TradeOrderResult;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import jdk.dynalink.linker.support.SimpleLinkRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 定时任务
 *
 * @author shenlang
 * @date 2024-06-11 15:52
 * @version  1.0.0
 * TODO 添加描述
 */
@Service
public class JobService {
    @Resource
    TradeOrderMapper tradeOrderMapper;
    @Resource
    ThreadPoolExecutor threadPoolExecutor;
    @Resource
    MailClient mailClient;
    @Value("${bill.path}")
    private String billPath;
    @Resource
    private UserPayInfoMapper userPayInfoMapper;

    @XxlJob("testJob")
    public void testJob(){
        System.out.println(DateUtil.now()+"Hi,你好哈哈!");
    }
    //生成每日对账单
    @XxlJob("bossEachDayBill")
    public void createEachDayBill() throws IOException {
        Date current = new Date();
        DateTime yesterday = DateUtil.offset(current, DateField.DAY_OF_MONTH, -1);
        DateTime beginDate = DateUtil.truncate(yesterday, DateField.DAY_OF_MONTH);
        DateTime endDate = DateUtil.truncate(current, DateField.DAY_OF_MONTH);
        System.out.println(beginDate+"\n"+endDate);
        //账单文件存储位置  81739922425681879042-20240108-bill.xlsx
        String dateString = new SimpleDateFormat("yyyyMMdd").format(current);
        System.out.println(dateString);
        //创建dateString对应的文件夹
        Path path = Paths.get(billPath,dateString);
        if(!Files.exists(path)){
            Files.createDirectories(path);
        }
        List<String> userNoList = tradeOrderMapper.selectUserBySuccessOrder(beginDate,endDate);
        userNoList.forEach((String userNo)->{
           List<TradeOrderResult> orderList =  tradeOrderMapper.selectOrdersByUserNo(userNo,beginDate,endDate);
            threadPoolExecutor.execute(()->{
                //生成excel文件
                String fileName = userNo+"-"+dateString+"-bill.xlsx";
                File file = Path.of(billPath,dateString,fileName).toFile();
                EasyExcel.write(file, EachDayBillHeader.class).sheet("商家每日对账单").doWrite(orderList);
            });
        });
    }
    //发送对账单邮件给商家
    @XxlJob("sendEachBill")
    public void sendEachBill(){
        Date current = new Date();
        DateTime yesterday = DateUtil.offset(current,DateField.DAY_OF_MONTH,-1);
        DateTime beginDate = DateUtil.truncate(yesterday,DateField.DAY_OF_MONTH);
        DateTime endDate = DateUtil.truncate(current,DateField.DAY_OF_MONTH);
        //需要知道持发送的商家userNo和userEmail
        List<UserInfo>  userInfos = userPayInfoMapper.selectBySuccessOrder(beginDate,endDate);
        //创建dateString对应的文件夹
        String dateString = new SimpleDateFormat("yyyyMMdd").format(current);
        userInfos.forEach((UserInfo userInfo)->{
            //账单文件
            threadPoolExecutor.execute(()->{
                String fileName = userInfo.getUserNo()+"-"+dateString+"-bill.xlsx";
                File file = Path.of(billPath,dateString,fileName).toFile();
                MailProp prop = new MailProp();
                prop.setFrom("changminghehe@163.com");
                prop.setTo(new String[]{userInfo.getUserEmail() });
                prop.setSubject("每日对账单");
                prop.setText(dateString+"网关发送给商家的每日对账单");
                AttachFile attachFile = new AttachFile(dateString+"对账单",file);
                prop.setAttachFiles(List.of(attachFile));
                mailClient.sendAttachMail(prop);
            });
        });
    }
}
